package com.qingge.springboot.controller;


import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qingge.springboot.common.Result;

import com.qingge.springboot.service.IMerchandiseService;
import com.qingge.springboot.entity.Merchandise;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Little_YIN
 * @since 2022-03-27
 */
@RestController
@RequestMapping("/merchandise")
public class MerchandiseController {
    @Resource
    private IMerchandiseService merchandiseService;

    /**
     * 导出接口 非代码生成器生成
     * 接口名：export
     * 这里需要在pom.xml中引入apache旗下的hutool依赖和poi-ooxml依赖
     * hutool version：5.7.20
     * poi-ooxml version：4.1.2
     *
     * @param response
     * @throws Exception
     */
    @GetMapping("/export")
    public void merchandiseExport(HttpServletResponse response) throws Exception {
        // 从数据库直接查出所有的数据
        List<Merchandise> list = merchandiseService.list();
        ExcelWriter writer = ExcelUtil.getWriter(true);

        writer.setDefaultRowHeight(12).write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");

        String fileName = URLEncoder.encode("商品信息", "utf-8");

        response.setHeader("Content-Disposition", "attachment;filename" + fileName + ".xlsx");

        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream, true);
        outputStream.close();
        writer.close();

    }

    /**
     * count merchandises table's numbers
     * @return CODE, msg, int merchandiseTotal data
     */
    @GetMapping("/total")
    public Result merchandiseTotal(){
        QueryWrapper<Merchandise> merchandiseQueryWrapper = new QueryWrapper<>();
        return Result.success(merchandiseService.count(merchandiseQueryWrapper));
    }

    @GetMapping("/stockCountZero")
    public Result stockCountZero(){
        QueryWrapper<Merchandise> merchandiseQueryWrapper = new QueryWrapper<>();
        merchandiseQueryWrapper.eq("stock",0);
        return Result.success(merchandiseService.count(merchandiseQueryWrapper));
    }
    /**
     * 导入接口 非代码生成器生成
     * 接口名：import
     * 这里需要在pom.xml中引入apache旗下的hutool依赖和poi-ooxml依赖
     * hutool version：5.7.20
     * poi-ooxml version：4.1.2
     *
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public boolean merchandiseImport(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader excelReader = ExcelUtil.getReader(inputStream);
//        excelReader.addHeaderAlias("id","货 号");
//        excelReader.addHeaderAlias("names","名 称");
//        excelReader.addHeaderAlias("specification","商品规格");
//        excelReader.addHeaderAlias("price","单 价");
//        excelReader.addHeaderAlias("stock","仓库余量");
        List<Merchandise> merchandiseList = excelReader.readAll(Merchandise.class);

        // 如果需要打印  则需要在Merchandise.java中加入@ToString注解
        // System.out.println(merchandiseList);
        merchandiseService.saveBatch(merchandiseList);
        return true;
    }

    // 新增或者更新
    @PostMapping
    public boolean save(@RequestBody Merchandise merchandise) {
        return merchandiseService.saveOrUpdate(merchandise);
    }

    @PostMapping("/deleteBatch") // 批量删除
    public boolean deleteBatch(@RequestBody List<Integer> ids) {
        return merchandiseService.removeByIds(ids);
    }

    @DeleteMapping("/delete/{id}") // 通过主键删除数据
    public Boolean delete(@PathVariable Integer id) {
        return merchandiseService.removeById(id);
    }

    @GetMapping
    public List<Merchandise> findAll() {
        return merchandiseService.list();
    }

    @GetMapping("/{id}") // 通过主键查询数据
    public Merchandise findOne(@PathVariable Integer id) {
        return merchandiseService.getById(id);
    }

    @GetMapping("/page") // 分页查询所有数据
    public IPage<Merchandise> merchandisePage(
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            @RequestParam(defaultValue = "") String names,
            @RequestParam(defaultValue = "") String specification
//            ,
//            @RequestParam(defaultValue = "") double price
    ) {
        IPage<Merchandise> merchandiseIPage = new Page<>(pageNum, pageSize);
        QueryWrapper<Merchandise> merchandiseQueryWrapper = new QueryWrapper<>();
        if (!"".equals(names)) {
            merchandiseQueryWrapper.like("names", names);
        }
        if (!"".equals(specification)) {
            merchandiseQueryWrapper.like("specification", specification);
        }
//        merchandiseQueryWrapper.like("price",price);
        merchandiseQueryWrapper.orderByDesc("id");
        return merchandiseService.page(merchandiseIPage, merchandiseQueryWrapper);

    }
}

